package promote.brozen.netty.jav.aio;

import lombok.Setter;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author Brozen
 * @date 2020/9/27 1:39 PM
 * @email brozen@qq.com
 */
public class AioReader implements CompletionHandler<Integer, AioReader> {

    private AsynchronousSocketChannel asc;

    private ByteBuffer buffer;

    @Setter
    private boolean echo = false;

    @Setter
    private String role = "Server";

    public AioReader(AsynchronousSocketChannel asc, ByteBuffer buffer) {
        this.asc = asc;
        this.buffer = buffer;
    }

    @Override
    public void completed(Integer result, AioReader attachment) {
        if (result < 0) {
            try {
                asc.close();
            } catch (IOException e) {
                System.out.println("关闭连接失败");
                e.printStackTrace();
            }
        }

        if (result <= 0) {
            return;
        }

        // 读取数据
        buffer.flip();
        byte[] data = new byte[buffer.remaining()];
        buffer.get(data);
        String msg = new String(data);
        System.out.println(role + "Receive: " + msg);

        // 准备下一次读取
        buffer.clear();
        asc.read(buffer, attachment, this);

        // 如果要返回
        if (echo) {
            String echoMsg = "Echo-> " + msg;
            byte[] echoData = echoMsg.getBytes();
            ByteBuffer buffer = ByteBuffer.allocate(echoData.length);
            buffer.put(echoData);
            buffer.flip();
            asc.write(buffer);
        }
    }

    @Override
    public void failed(Throwable exc, AioReader attachment) {
        System.out.println("读取客户端数据失败!");
    }

}
